package xyz.kongbai121.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import xyz.kongbai121.common.exception.RRException;
import xyz.kongbai121.common.utils.PageUtils;
import xyz.kongbai121.common.utils.Query;
import xyz.kongbai121.modules.sys.dao.FileUploadLocalDao;
import xyz.kongbai121.modules.sys.entity.FileUploadLocalEntity;
import xyz.kongbai121.modules.sys.service.FileUploadLocalService;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import java.util.UUID;


@Service("fileUploadLocalService")
@ConfigurationProperties(prefix = "kongbai.file")
public class FileUploadLocalServiceImpl extends ServiceImpl<FileUploadLocalDao, FileUploadLocalEntity> implements FileUploadLocalService {
    @Setter@Getter
    private String filePath;
    @Setter @Getter
    private String parentFolder;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        LambdaQueryWrapper<FileUploadLocalEntity> wrapper = new LambdaQueryWrapper<>();

        IPage<FileUploadLocalEntity> page = this.page(
                new Query<FileUploadLocalEntity>().getPage(params),
                wrapper.orderByDesc(FileUploadLocalEntity::getUpdateTime)
        );

        return new PageUtils(page);
    }

    @Override
    public FileUploadLocalEntity downloadFromUrlAndSave(String httpUrl) throws IOException {

        Date date = new Date();

        // 文件保存逻辑
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        String folderName = filePath + parentFolder + simpleDateFormat.format(date);
        File parent = new File(parentFolder);
        if (!parent.exists() || !parent.isDirectory()){
            boolean mkdir = parent.mkdir();
        }
        File folder = new File(folderName);
        if (!folder.exists() || !folder.isDirectory()){
            boolean mkdir = folder.mkdir();
        }

        // 服务器文件名
        String serverFileName = UUID.randomUUID().toString() + httpUrl.substring(httpUrl.lastIndexOf("."));
        // 文件路径
        String serverFile = folderName + "/" + serverFileName;
        File file = new File(serverFile);

        URL url = new URL(httpUrl);
        ReadableByteChannel rbc = Channels.newChannel(url.openStream());
        FileOutputStream fos = new FileOutputStream(file);
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        fos.close();
        rbc.close();

        FileUploadLocalEntity fileUploadLocal = new FileUploadLocalEntity();
        fileUploadLocal.setPath(serverFile);
        fileUploadLocal.setSrc(parentFolder + simpleDateFormat.format(date) + "/" + serverFileName);
        this.save(fileUploadLocal);
        return fileUploadLocal;
    }

    @Override
    public FileUploadLocalEntity uploadAndSave(MultipartFile file) throws IOException {
        if (file ==null || file.getSize()<=0 || StringUtils.isBlank(file.getOriginalFilename())){
            throw new RRException("请勿上传空文件!");
        }
        Date date = new Date();

        // 文件保存逻辑
        String orgFileName = file.getOriginalFilename();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        String folderName = filePath + parentFolder + simpleDateFormat.format(date);
        File parent = new File(parentFolder);
        if (!parent.exists() || !parent.isDirectory()){
            boolean mkdir = parent.mkdir();
        }
        File folder = new File(folderName);
        if (!folder.exists() || !folder.isDirectory()){
            boolean mkdir = folder.mkdir();
        }

        // 服务器文件名
        String serverFileName = UUID.randomUUID().toString() + orgFileName.substring(orgFileName.lastIndexOf("."));
        // 文件路径
        String serverFile = folderName + "/" + serverFileName;
        File co = new File(serverFile);
        Files.copy(file.getInputStream(),co.toPath());
        FileUploadLocalEntity fileUploadLocal = new FileUploadLocalEntity();
        fileUploadLocal.setPath(serverFile);
        fileUploadLocal.setSrc(parentFolder + simpleDateFormat.format(date) + "/" + serverFileName);
        this.save(fileUploadLocal);
        return fileUploadLocal;
    }

    @Override
    public FileUploadLocalEntity getById(Serializable id) {
        return super.getById(id);
    }

    @Override
    public boolean save(FileUploadLocalEntity entity) {
        return super.save(entity);
    }

    @Override
    public boolean updateById(FileUploadLocalEntity entity) {
        return super.updateById(entity);
    }

    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        return super.removeByIds(idList);
    }

}